#include <math.h>

#include "setupwindow.h"
#include "ui_setupwindow.h"



SetupWindow::SetupWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SetupWindow)
{
    ui->setupUi(this);
//    this->resize(QApplication::desktop()->size());
//    this->showFullScreen();

    centerX = (width() / 2);
    centerY = (height() / 2);




}

SetupWindow::~SetupWindow()
{   
    delete ui;
}

void SetupWindow::on_doneSelecting(const QString &newDifficulty, const QString &newMode, const QString &newName) {

    difficulty = newDifficulty;
    mode = newMode;
    username = newName;
    GameWorld::instance().setUserName(newName);
    QDir saveDir("saves/" + username);
    if (saveDir.exists()) {
        if (QMessageBox::Yes == QMessageBox::question(this, "Save Data exists", "Do you want to load your previous game, " + username + "?", QMessageBox::Yes, QMessageBox::No)) {
            GameWorld::instance().loadGame();
            repaint();
            show();
            drawTileGrid("player");
            drawShips();
            drawTileGrid("ai");
            ui->btnDonePlacing->hide();
            ui->btnRearrangeShips->hide();
            ui->btnUpdateShips->hide();
            ui->lblTime->hide();
            ui->lcdNumber->hide();
            ui->btnResign->setEnabled(true);
            ui->btnSaveGame->setEnabled(true);
            ui->btnCheat->setEnabled(true);
            redrawShots();
            updateTiles();
            updateShips();
            return;
        }
    }
    ui->lblTime->hide();
    ui->lcdNumber->hide();
    ui->btnResign->setEnabled(true);
    ui->btnSaveGame->setEnabled(true);
    ui->btnRearrangeShips->show();
    ui->btnDonePlacing->show();

    repaint();
    show();
    buildTileGrid("player");
    drawTileGrid("player");
    drawShips();
    buildTileGrid("ai");
    GameWorld::instance().setCheatMode(false);
    GameWorld::instance().setScore(0);

}

void SetupWindow::buildTileGrid(QString whichPlayer) {
    WorldBuilder builder;
//    int newx = centerX - 160; // true center
//    int newy = centerY - 160;
    size_t newx, newy;
    if (whichPlayer == "player") {
        //coordinates for the setup phase grid
//        newx = centerX - 360;
//        newy = centerY - 160;
        newx = ui->frameGridPlayer->x();
        newy = ui->frameGridPlayer->y();
    } else if (whichPlayer == "ai") {
        //need to store ai tiles in a separate vector
//        newx = centerX + 160;
//        newy = centerY - 160;
        newx = ui->frameGridPlayer_2->x();
        newy = ui->frameGridPlayer_2->y();
    }



    //set the current difficulty
    GameWorld::instance().setDifficulty(difficulty);

    // build different size grids based
    // on difficulty
    if (difficulty == "easy") {
        // create 8x8 grid of water

        //create all tiles in a column at a time
        for (size_t i = 0; i < 8; ++i) {
            //            int newy = centerY - 160; //reset y
            if (whichPlayer == "player") {
                newy = ui->frameGridPlayer->y();
                CreateTileCommand *cmd = new CreateTileCommand("water", newy, newx, "watertile");
                builder.doCommand(cmd);
            } else {
                newy = ui->frameGridPlayer_2->y();
                CreateOpponentTileCommand *cmd = new CreateOpponentTileCommand("water", newy, newx, "watertile");
                builder.doCommand(cmd);
            }


            for (size_t i = 0; i < 7; ++i) {
                newy = newy + 40;
                if (whichPlayer == "player") {
                    CreateTileCommand *cmd = new CreateTileCommand("water", newy, newx, "watertile");
                    builder.doCommand(cmd);
                } else {
                    CreateOpponentTileCommand *cmd = new CreateOpponentTileCommand("water", newy, newx, "watertile");
                    builder.doCommand(cmd);
                }

            }
            newx = newx + 40; //shift to next column
        }

        // create the ships
        // randomize for now

//        int shipX = centerX - 160, shipY = centerY - 160;
//        vector<string> shipstobuild;
//        shipstobuild.push_back("battleship");
//        shipstobuild.push_back("submarine");
//        shipstobuild.push_back("destroyer");
//        shipstobuild.push_back("aircraftcarrier");
//        shipstobuild.push_back("cruiser");
//        for (size_t i = 0; i < 5; ++i) {
//            //generate random orientation
//            bool portrait = false;
////            int randomNum = (rand() % 40) + 10;
////            if (randomNum < 30)
////                portrait = true;

//            CreateShipCommand *cmd = new CreateShipCommand(shipstobuild.at(i), shipstobuild.at(i), shipX, shipY, portrait);
//            builder.doCommand(cmd);
//            shipY = shipY + 40;
//        }
        //make a separate method to test the total amount of ship hp (all ships combined) against
        //the total number of ship tiles, if number of ship tiles < total hp, then try placing ships randomly again
        //this protects against overlapping ships

        //see if right number of tiles were creating
        // for testing only
        int numTiles = GameWorld::instance().getWaterTiles().size();
        int numOpTiles = GameWorld::instance().getOpponentWaterTiles().size();

        if (whichPlayer == "player") {
            //ai places ships for the player
            aiplayer = new Player(this);
            aiplayer->placeShip("aircraftcarrier", whichPlayer);
            aiplayer->placeShip("battleship", whichPlayer);
            aiplayer->placeShip("cruiser", whichPlayer);
            aiplayer->placeShip("submarine", whichPlayer);
            aiplayer->placeShip("destroyer", whichPlayer);
        } else {
            //place the ai's ships
            aiplayer = new Player(this);
            aiplayer->placeShip("aircraftcarrier", whichPlayer);
            aiplayer->placeShip("battleship", whichPlayer);
            aiplayer->placeShip("cruiser", whichPlayer);
            aiplayer->placeShip("submarine", whichPlayer);
            aiplayer->placeShip("destroyer", whichPlayer);
        }

        //for testing purposes
        //to test hp
//        QList<ShipObject> testships = GameWorld::instance().getPlayerShips();
//        ShipObject testShip = testships.at(1);

//        int hp = testShip.getHp();

    }

}

void SetupWindow::rearrangeShips() {
    aiplayer = new Player(this);
    aiplayer->placeShip("aircraftcarrier", "player");
    aiplayer->placeShip("battleship", "player");
    aiplayer->placeShip("cruiser", "player");
    aiplayer->placeShip("submarine", "player");
    aiplayer->placeShip("destroyer", "player");
//    QList<ShipObject> templist = GameWorld::instance().getPlayerShips();
//    ShipObject curship = templist.at(2);
    //    syncTilesAndShips("player");

}

void SetupWindow::redrawShots()
{
    vector<WaterTile*>& playertiles = GameWorld::instance().getWaterTiles();
    QPixmap watertile_miss(":/images/watertile_miss.png");
    QPixmap ship_hit(":/images/ship_hit.png");
    QLabel *label;
    WaterTile *curtile;
    for (size_t i = 0; i < playertiles.size(); ++i) {
        curtile = playertiles[i];
        int x, y;
        x = ui->frameGridPlayer->x();
        y = ui->frameGridPlayer->y();
        if (curtile->getType() == "ship" && curtile->isHit())
        {
            label = new QLabel(this);
            label->setPixmap(ship_hit);
            label->setGeometry(curtile->getCol(), curtile->getRow(), ship_hit.width(), ship_hit.height());
            label->show();
        }
        else if (curtile->isHit()){
            label = new QLabel(this);
            label->setPixmap(watertile_miss);
            label->setGeometry(curtile->getCol(), curtile->getRow(), watertile_miss.width(), watertile_miss.height());
            int col, row;
            col = curtile->getCol();
            row = curtile->getRow();
            label->show();
        }
    }

}

// draw the grid
void SetupWindow::drawTileGrid(QString whichPlayer) {
    QPixmap watertile(":/images/watertile.png");
    QPixmap watertileclicked(":/images/watertilehover.png");
//    QPixmap watertilehit(":/images/watertilehit.png");
//    QPixmap watertilemiss(":/images/watertilemiss.png");

    //store ai tiles in a different vector

    vector<WaterTile*>& tilestodraw = GameWorld::instance().getWaterTiles();
    vector<WaterTile*>& opponenttiles = GameWorld::instance().getOpponentWaterTiles();
    size_t whichvectorlength;
    size_t i = 0;
//    if (whichPlayer == "player") {
        whichvectorlength = tilestodraw.size();
//    } else {
//        whichvectorlength = opponenttiles.size();
//    }

    //draw the tiles depending on whose vector of tiles it is
    while ( i < whichvectorlength) {
        WaterTile *curTile;
        if (whichPlayer == "player") {
            curTile = tilestodraw.at(i);
        } else {
            curTile = opponenttiles.at(i);
        }

        DynaLabel *curLabel = new DynaLabel(this, curTile->getId()); //will be curTile->getType() once we add more types
        connect(curLabel, SIGNAL(tileClicked()), SLOT(on_tileClicked()));

        //find and set current image property
        if (curTile->getType() == "water" || curTile->getType() == "ship" ){
            if (curTile->isSelected()){
                curLabel->setPixmap(watertileclicked);                
            }
            else{
                curLabel->setPixmap(watertile);
                curTile->setSelected(false);
            }


        } else {
            curLabel->setText("Error");
        }

//        if (curTile->getType() == "normal") {
//            curLabel->setPixmap(watertile);
//            curTile->setSelected(false);
//        } else if (curTile->getType() == "clicked") {
//            curLabel->setPixmap(watertileclicked);
//            //curTile->setSelected(true);
//        } else {
//            curLabel->setText("Error");
//        }

        curLabel->setGeometry(curTile->getCol(), curTile->getRow(), watertile.width(), watertile.height());
        if (curTile->getType() == "ship") {
            curLabel->setType("ship");
            curLabel->setTypeShip(curTile->getTypeShip());
        } else {
            curLabel->setType("water");
        }
        if (whichPlayer == "player") {
            addWaterTileLabel(curLabel);
        } else {
            addOpponentWaterTileLabel(curLabel);
        }
        curLabel->show();
        ++i;
    }
}

//update tile grid
void SetupWindow::updateTiles() {
    QPixmap watertile(":/images/watertile.png");
    QPixmap watertileclicked(":/images/watertilehover.png");
    QPixmap watertile_miss(":/images/watertile_miss.png");
    QPixmap ship_hit(":/images/ship_hit.png");

    //for cheat mode
    QPixmap ship_cheat(":/images/ship_cheat.png");

    //see if right number of tiles were creating
    // for testing only
    int numTiles = GameWorld::instance().getWaterTiles().size();
    int numOpTiles = GameWorld::instance().getOpponentWaterTiles().size();

    vector<WaterTile*>& tilestoredraw = GameWorld::instance().getOpponentWaterTiles();

    vector<DynaLabel*>& labels = getOpponentWaterTileLabels();

    for (size_t i = 0; i < tilestoredraw.size(); ++i) {
        WaterTile *curtile = tilestoredraw.at(i);
        DynaLabel *curlabel = labels.at(i);
        if (curtile->isSelected() && !curtile->isHit()) {            
            curlabel->setPixmap(watertileclicked);
            curlabel->show();
//            return; //don't need to loop through the rest of the tiles //this was causing problemsf

        } else if (curtile->getType() == "water" && curtile->isHit()) {            
            curlabel->setPixmap(watertile_miss);
            curlabel->show();
        } else if (curtile->getType() == "water" && !curtile->isHit()){            
            curlabel->setPixmap(watertile);
            curlabel->show();
        } else if (curtile->getType() == "ship" && curtile->isHit()) {           
            curlabel->setPixmap(ship_hit);
            curlabel->show();
        } else if (curtile->getType() == "ship" && !curtile->isHit()) {
            if (GameWorld::instance().getCheatMode() == true)
               curlabel->setPixmap(ship_cheat);
            else
                curlabel->setPixmap(watertile);
            curlabel->show();
        }
    }
}

//draw ship labels
void SetupWindow::drawShips() {
    QPixmap battleship(":/images/battleship.png");
    QPixmap battleship_portrait(":/images/battleship_portrait.png");
    QPixmap cruiser(":/images/cruiser.png");
    QPixmap cruiser_portrait(":/images/cruiser_portrait.png");
    QPixmap submarine(":/images/submarine.png");
    QPixmap submarine_portrait(":/images/submarine_portrait.png");
    QPixmap aircraftcarrier(":/images/aircraftcarrier.png");
    QPixmap aircraftcarrier_portrait(":/images/aircraftcarrier_portrait.png");
    QPixmap destroyer(":/images/destroyer.png");
    QPixmap destroyer_portrait(":/images/destroyer_portrait.png");
//    vector<ShipObject*> shipstodraw = GameWorld::instance().getShipObjects();

    //using the player class ai to randomly place ships, need playerships list
    QList<ShipObject>& shipstodraw = GameWorld::instance().getPlayerShips();

    // need to figure out how to change the col and row from integers to actual pixel locations for the labels
    // need to check orientation of ship also
    for (size_t i = 0; i < shipstodraw.size(); ++i) {
        ShipObject curship = shipstodraw.at(i);
        //calculate curship coordinates
        int curX, curY;
        curX = (curship.getCol() * 40) + (ui->frameGridPlayer->x());
        curY = (curship.getRow() * 40) + (ui->frameGridPlayer->y());
        DynaLabel *label = new DynaLabel(this, curship.getId());
        if (curship.getImage() == "battleship") {
            if (curship.getImage().contains("portrait")) {
                label->setPixmap(battleship_portrait);
                label->setGeometry(curX, curY, battleship_portrait.width(), battleship_portrait.height());
            } else {
                label->setPixmap(battleship);
                label->setGeometry(curX, curY, battleship.width(), battleship.height());
            }
            label->setGeometry(curX, curY, battleship.width(), battleship.height());
        } else if (curship.getImage().contains("cruiser")) {
            if (curship.getImage().contains("portrait")) {
                label->setPixmap(cruiser_portrait);
                label->setGeometry(curX, curY, cruiser_portrait.width(), cruiser_portrait.height());
            } else {
                label->setPixmap(cruiser);
                label->setGeometry(curX, curY, cruiser.width(), cruiser.height());
            }
        } else if (curship.getImage().contains("submarine")) {
            if (curship.getImage().contains("portrait")) {
                label->setPixmap(submarine_portrait);
                label->setGeometry(curX, curY, submarine_portrait.width(), submarine_portrait.height());
            } else {
                label->setPixmap(submarine);
                label->setGeometry(curX, curY, submarine.width(), submarine.height());
            }
        } else if (curship.getImage().contains("aircraftcarrier")) {
            if (curship.getImage().contains("portrait")) {
                label->setPixmap(aircraftcarrier_portrait);
                label->setGeometry(curX, curY, aircraftcarrier_portrait.width(), aircraftcarrier_portrait.height());
            } else {
                label->setPixmap(aircraftcarrier);
                label->setGeometry(curX, curY, aircraftcarrier.width(), aircraftcarrier.height());
            }
        } else if (curship.getImage() == "destroyer") {
            if (curship.getImage().contains("portrait")) {
                label->setPixmap(destroyer_portrait);
                label->setGeometry(curX, curY, destroyer_portrait.width(), destroyer_portrait.height());
            } else {
                label->setPixmap(destroyer);
                label->setGeometry(curX, curY, destroyer.width(), destroyer.height());
            }
        }
        connect(label, SIGNAL(shipClicked()), SLOT(on_ship_clicked()));
        addShipLabel(label);
        label->show();
    }
}

//update ship labels
void SetupWindow::updateShips() {
    QPixmap battleship(":/images/battleship.png");
    QPixmap battleship_portrait(":/images/battleship_portrait.png");
    QPixmap cruiser(":/images/cruiser.png");
    QPixmap cruiser_portrait(":/images/cruiser_portrait.png");
    QPixmap submarine(":/images/submarine.png");
    QPixmap submarine_portrait(":/images/submarine_portrait.png");
    QPixmap aircraftcarrier(":/images/aircraftcarrier.png");
    QPixmap aircraftcarrier_portrait(":/images/aircraftcarrier_portrait.png");
    QPixmap destroyer(":/images/destroyer.png");
    QPixmap destroyer_portrait(":/images/destroyer_portrait.png");



    //needs to be modified to work with all ships, not just battleships
    vector<DynaLabel*> shiplabels = getShipLabels();
    QList<ShipObject>& ships = GameWorld::instance().getPlayerShips();
    for (size_t i = 0; i < ships.size(); ++i) {
        ShipObject curship = ships.at(i);
        //calculate curship coordinates
        int curX, curY;
        curX = (curship.getCol() * 40) + (ui->frameGridPlayer->x());
        curY = (curship.getRow() * 40) + (ui->frameGridPlayer->y());

        // do not need to select ships
//        if (curship.isSelected()) {
//            DynaLabel *curlabel = shiplabels.at(i);
//            if (curship.getImage() == "battleship") {
//                curlabel->setPixmap(battleshipselected);
//                curlabel->setGeometry(curship.getCol(), curship.getRow(), battleship.width(), battleship.height());
////          } else if (curship->getImage() == "cruiser") {
////                curlabel->setPixmap(cruiser);
////          } else if (curship->getImage() == "submarine") {
////                curlabel->setPixmap(submarine);
//            } else if (curship.getImage().contains("aircraftcarrier")) {
//                if (curship.getImage().contains("portrait")) {
//                    curlabel->setPixmap(aircraftcarrier_sel_portrait);
//                    curlabel->setGeometry(curX, curY, aircraftcarrier_sel_portrait.width(), aircraftcarrier_sel_portrait.height());
//                } else {
//                    curlabel->setPixmap(aircraftcarrier_sel);
//                    curlabel->setGeometry(curX, curY, aircraftcarrier.width(), aircraftcarrier.height());
//                }

////          } else if (curship->getImage() == "destroyer") {
////                curlabel->setPixmap(destroyer);
//            }
//            curlabel->show();
//        } else {
            DynaLabel *curlabel = shiplabels.at(i);
            if (curship.getImage().contains("battleship")) {
                if (curship.getImage().contains("portrait")) {
                    curlabel->setPixmap(battleship_portrait);
                    curlabel->setGeometry(curX, curY, battleship_portrait.width(), battleship_portrait.height());
                } else {
                    curlabel->setPixmap(battleship);
                    curlabel->setGeometry(curX, curY, battleship.width(), battleship.height());
                }
            }
            else if (curship.getImage().contains("cruiser")) {
                if (curship.getImage().contains("portrait")) {
                    curlabel->setPixmap(cruiser_portrait);
                    curlabel->setGeometry(curX, curY, cruiser_portrait.width(), cruiser_portrait.height());
                } else {
                    curlabel->setPixmap(cruiser);
                    curlabel->setGeometry(curX, curY, cruiser.width(), cruiser.height());
                }
            }
            else if (curship.getImage().contains("submarine")) {
                if (curship.getImage().contains("portrait")) {
                    curlabel->setPixmap(submarine_portrait);
                    curlabel->setGeometry(curX, curY, submarine_portrait.width(), submarine_portrait.height());
                } else {
                    curlabel->setPixmap(submarine);
                    curlabel->setGeometry(curX, curY, submarine.width(), submarine.height());
                }
            }
            else if (curship.getImage().contains("aircraftcarrier")) {
                if (curship.getImage().contains("portrait")) {
                    curlabel->setPixmap(aircraftcarrier_portrait);
                    curlabel->setGeometry(curX, curY, aircraftcarrier_portrait.width(), aircraftcarrier_portrait.height());
                } else {
                curlabel->setPixmap(aircraftcarrier);
                curlabel->setGeometry(curX, curY, aircraftcarrier.width(), aircraftcarrier.height());
                }
            }
            else if (curship.getImage().contains("destroyer")) {
                if (curship.getImage().contains("portrait")) {
                    curlabel->setPixmap(destroyer_portrait);
                    curlabel->setGeometry(curX, curY, destroyer_portrait.width(), destroyer_portrait.height());
                } else {
                curlabel->setPixmap(destroyer);
                curlabel->setGeometry(curX, curY, destroyer.width(), destroyer.height());
                }
            }
            curlabel->show();
        }

}

void SetupWindow::addWaterTileLabel(DynaLabel *newLabel) {
    watertilelabels.push_back(newLabel);
}

void SetupWindow::addOpponentWaterTileLabel(DynaLabel *newLabel) {
    opponentwatertilelabels.push_back(newLabel);

}

void SetupWindow::addShipLabel(DynaLabel *newLabel) {
    shiplabels.push_back(newLabel);
}


void SetupWindow::on_tileClicked()
{
    updateTiles();
    ui->btnFire->setEnabled(true);
}




void SetupWindow::on_btnMoveRight_clicked()
{
    QList<ShipObject>& currentShips = GameWorld::instance().getOpponentShips();
    //find which ship is selected
    for (size_t i = 0; i < currentShips.size(); ++i) {
        ShipObject curShip = currentShips.at(i);
        if (curShip.isSelected()) {
            //move the ship to the right by 40 pixels
            //figure out how to not let it go past the boundaries of the grid...
            //centerX + 160 is the right bound for easy mode
            //centerY + 160 is the bottom bound, and so forth
            if (curShip.getImage() == "aircraftcarrier") {
                //must check difficulty depending on size of grid
                if (difficulty == "easy") {
                    if (curShip.getCol() <= centerY+40) {
                        curShip.setCol(curShip.getCol() + 40);
                        break;
                    } else {
                        break;
                    }
                }
                //add other difficulties later

            } else if (curShip.getImage() == "battleship") {
                if (difficulty == "easy") {
                    if (curShip.getCol() <= centerY+80) {
                        curShip.setCol(curShip.getCol() + 40);
                        break;
                    } else {
                        break;
                    }
                }
            }

        }
    }
    updateShips();
}

void SetupWindow::on_btnRearrangeShips_clicked()
{
    rearrangeShips();
//    syncTilesAndShips("player");
    updateShips();
}

void SetupWindow::on_btnDonePlacing_clicked()
{
    ui->btnRearrangeShips->hide();
    ui->btnDonePlacing->hide();
    ui->btnCheat->setEnabled(true);
    ui->lblTime->show();
    ui->lcdNumber->show();
    syncTilesAndShips("player");
    updateShips();
    syncTilesAndShips("ai");    
    drawTileGrid("ai");

    QList<ShipObject> tempShips = GameWorld::instance().getPlayerShips();
    foreach (ShipObject tempship, tempShips) {
        QString tempstr = QString::fromStdString(tempship.toString());
        qDebug() << tempstr;
    }

}



void SetupWindow::on_btnFire_clicked()
{
    bool shipsunk = false;
    // if tile selected
    vector<WaterTile*>& temptiles = GameWorld::instance().getOpponentWaterTiles();

    //see if right number of tiles were creating
    // for testing only
    int numTiles = GameWorld::instance().getWaterTiles().size();
    int numOpTiles = GameWorld::instance().getOpponentWaterTiles().size();

    WaterTile *curtile;
    for (size_t i =0; i < temptiles.size(); ++i) {
        curtile = temptiles.at(i);
        if (curtile->isSelected()) {
            curtile->setSelected(false);
            shipsunk = GameWorld::instance().Fire(curtile, "player");
            updateTiles();
            break;
        }
    }
    ui->lblScrNum->setText(QString::number(GameWorld::instance().getScore()));
    emit playerFired();
    if (shipsunk) {
        emit shipSunk("player", "ai", curtile->getTypeShip());
    }
}

void SetupWindow::on_btnFire_released()
{
    ui->btnFire->setEnabled(false);   
}

void SetupWindow::on_playerFired()
{
    bool shipsunk = false;
    vector<WaterTile*>& temptiles = GameWorld::instance().getWaterTiles();

    int randInt = qrand() % ((64) - 0) + 0;
    WaterTile *curtile = temptiles.at(randInt);

    while (curtile->isHit()){
        randInt = qrand() % ((64) - 0) + 0;
        curtile = temptiles.at(randInt);
    }
    if (!curtile->isHit())
    {
        shipsunk = GameWorld::instance().Fire(curtile, "ai");
        QPixmap watertile_miss(":/images/watertile_miss.png");
        QPixmap ship_hit(":/images/ship_hit.png");
        QLabel *label = new QLabel(this);
        int x, y;
        x = ui->frameGridPlayer->x();
        y = ui->frameGridPlayer->y();
        if (curtile->getType() == "ship")
        {

            label->setPixmap(ship_hit);
            label->setGeometry(curtile->getCol(), curtile->getRow(), ship_hit.width(), ship_hit.height());
            label->show();
        }
        else {
            label->setPixmap(watertile_miss);
            label->setGeometry(curtile->getCol(), curtile->getRow(), watertile_miss.width(), watertile_miss.height());
            int col, row;
            col = curtile->getCol();
            row = curtile->getRow();
            label->show();
        }

        //updateOpTiles();
    }

    if (shipsunk) {
        emit shipSunk("AI", "player", curtile->getTypeShip());
    }



}

void SetupWindow::syncTilesAndShips(QString whichPlayer)
{
    //for demonstration, will mirror player's ships
//    QList<ShipObject>& shipstosync = GameWorld::instance().getPlayerShips();
//    ShipObject curship;curLabel->setType("water");

    QList<ShipObject> *opponentships;
    if (whichPlayer == "player") {
        opponentships = &GameWorld::instance().getPlayerShips();
    } else {
        opponentships = &GameWorld::instance().getOpponentShips();
    }

    ShipObject curopship;
//    vector<WaterTile*> tilestosync = GameWorld::instance().getOpponentWaterTiles();


    vector<WaterTile*> *tilestosync;
    if (whichPlayer == "player") {
        tilestosync = &GameWorld::instance().getWaterTiles();
    } else{
        tilestosync = &GameWorld::instance().getOpponentWaterTiles();
    }

    //see if right number of tiles were creating
    // for testing only
    int numTiles = GameWorld::instance().getWaterTiles().size();
    int numOpTiles = GameWorld::instance().getOpponentWaterTiles().size();


    for (size_t i = 0; i < opponentships->size(); ++i) {
//        curship = shipstosync.at(i);
        curopship = opponentships->at(i);
//        WaterTile *curtile;
        WaterTile *curoptile;
        for (size_t j = 0; j < tilestosync->size(); ++j) {
//            curtile = tilestosync.at(j);
            curoptile = tilestosync->at(j);
            //tile coordinates are pixel coords while ship coords are grid coordinates
            //calculate curship coordinates

            int frameX = ui->frameGridPlayer->x();
            int frameY = ui->frameGridPlayer->y();
            int frame2X = ui->frameGridPlayer_2->x();
            int frame2Y = ui->frameGridPlayer_2->y();
            int curX = (curopship.getCol() * 40) + frameX;
            int cur2X = (curopship.getCol() * 40) + frame2X;
            int curY = (curopship.getRow() * 40) + frameY;
            int cur2Y = (curopship.getRow() * 40) + frame2Y;

            //do player's ships
            if (whichPlayer == "player") {
                if (curX == curoptile->getCol() && curY == curoptile->getRow()) {
                    curoptile->setType("ship");
                    curoptile->setTypeShip(curopship.getImage());
                    if (curopship.isPortrait()) {
                        for (size_t y = 1; y < curopship.getHp(); ++y) {
                            curoptile = tilestosync->at(j + y);
                            curoptile->setType("ship");
                            curoptile->setTypeShip(curopship.getImage());
                        }
                        break;
                    } else {
                        size_t tileDistance = 8;
                        while (tileDistance < (curopship.getHp() * 8)) {
                            curoptile = tilestosync->at(j + tileDistance);
                            curoptile->setType("ship");
                            curoptile->setTypeShip(curopship.getImage());
                            tileDistance = tileDistance + 8;
                        }
                        break;
                    }

                }
            } else {

                //do computer's ships
                if (cur2X == curoptile->getCol() && cur2Y == curoptile->getRow()) {
                    curoptile->setType("ship");
                    curoptile->setTypeShip(curopship.getImage());

                    if (curopship.isPortrait()) {
                        for (size_t y = 1; y < curopship.getHp(); ++y) {
                            curoptile = tilestosync->at(j + y);
                            curoptile->setType("ship");
                            curoptile->setTypeShip(curopship.getImage());
                        }
                        break;
                    } else {
                        size_t tileDistance = 8;
                        while (tileDistance < (curopship.getHp() * 8)) {
                            curoptile = tilestosync->at(j + tileDistance);
                            curoptile->setType("ship");
                            curoptile->setTypeShip(curopship.getImage());
                            tileDistance = tileDistance + 8;
                        }
                        break;
                    }

                }
            }

        }
    }
}

void SetupWindow::on_btnUpdateShips_clicked()
{
    updateShips();
}

void SetupWindow::on_btnCheat_clicked()
{
    if (GameWorld::instance().getCheatMode() == false)
        GameWorld::instance().setCheatMode(true);
    else
        GameWorld::instance().setCheatMode(false);

    updateTiles();

}

void SetupWindow::on_shipSunk(QString whichPlayer, QString whichVictim, QString whichShip)
{
    if (whichShip.contains("_")) {
        whichShip = whichShip.remove(whichShip.indexOf("_"), whichShip.size());
    }
    if (whichPlayer == "player") {
        ui->lblInformation->setText(username + " has sunk " + whichVictim + "'s " + whichShip + "!");
    } else {
        ui->lblInformation->setText("AI has sunk " + username + "'s " + whichShip + "!");
    }
    GameWorld::instance().decShips(whichVictim);
    if (GameWorld::instance().getNumShips(whichVictim) == 0) {
        emit playerWon(whichPlayer);
    }
}

void SetupWindow::on_playerWon(QString whichPlayer)
{
    if (whichPlayer == "player") {
         QMessageBox::information(this, "Game Over!", username + " has won!");
    } else {
        QMessageBox::information(this, "Game Over!", whichPlayer + " has won!");
    }
    emit newGame();
    GameWorld::instance().resetWorld();
    close();
}

void SetupWindow::on_btnResign_clicked() {
    if (QMessageBox::Yes == QMessageBox::question(this, "Resign?", "Do you really want to quit, " + username + "?", QMessageBox::Yes, QMessageBox::No)) {
        close();
    }
}

void SetupWindow::on_btnSaveGame_clicked()
{
    QDir newsaveDir("saves/");
    if (!newsaveDir.exists()) {
        QDir().mkdir("saves");
    }
    QDir saveDir("saves/" + username);
    if (saveDir.exists()) {
        if (QMessageBox::Yes == QMessageBox::question(this, "Save Data exists", "Do you want to overwrite your data, " + username + "?", QMessageBox::Yes, QMessageBox::No)) {
            GameWorld::instance().saveGame();
        }
    }
    GameWorld::instance().saveGame();
}

void SetupWindow::on_btnLoad_clicked()
{
    GameWorld::instance().loadGame();
}
